package com.glitter.player.springbootmultipledatasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        JdbcTemplateAutoConfiguration.class
})
@Slf4j
public class SpringbootMultipleDatasourceApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMultipleDatasourceApplication.class, args);
    }

    @Bean
    @ConfigurationProperties("head.datasource")
    public DataSourceProperties headDataSourceProperties(){
    return new DataSourceProperties();
    }
    @Bean
    @Primary
    public DataSource headDatasource() {
        DataSourceProperties dataSourceProperties = headDataSourceProperties();
        log.info("head datasource: {}", dataSourceProperties.getUrl());
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
    @Bean
    public PlatformTransactionManager headTransactionManager(DataSource headDatasource){
        return new DataSourceTransactionManager(headDatasource);
    }
    @Bean
    public JdbcTemplate headJdbcTemplate( DataSource headDatasource) {
        return new JdbcTemplate(headDatasource);
    }




    @Bean
    @ConfigurationProperties("foot.datasource")
    public DataSourceProperties footDataSourceProperties(){
        return new DataSourceProperties();
    }
    @Bean
    public PlatformTransactionManager footTransactionManager(DataSource footDatasource){
        return new DataSourceTransactionManager(footDatasource);
    }

    @Bean
    public DataSource footDataSource() {
        DataSourceProperties dataSourceProperties = footDataSourceProperties();
        log.info("foot datasource: {}", dataSourceProperties.getUrl());
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
    @Bean(name = "footJdbcTemplate")
    public JdbcTemplate footJdbcTemplate( DataSource footDatasource) {
        return new JdbcTemplate(footDatasource);
    }



}
